package com.lxiaodd.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.lxiaodd.common.Common;
import com.lxiaodd.model.Income;
import com.lxiaodd.service.IncomeService;
import com.lxiaodd.service.OutService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;

@WebServlet(name = "WxMpServlet", urlPatterns = {"/wechat"})
public class WxMpServlet extends HttpServlet {
	/**
	* 
	*/
	private static final long serialVersionUID = 1L;
	protected WxMpInMemoryConfigStorage config;
	protected WxMpService wxMpService;
	protected WxMpMessageRouter wxMpMessageRouter;
	protected OutService outService;
	protected IncomeService incomeService;

	@Override
	public void init() throws ServletException {
		super.init();
		config = new WxMpInMemoryConfigStorage();
		config.setAppId("wx599872cc5f024bae"); // 设置微信公众号的appid
		config.setSecret("fdce60047ec12654ae679c714ed0a18c"); // 设置微信公众号的app corpSecret
		config.setToken("lxiaodtoken"); // 设置微信公众号的token
		config.setAesKey("4MmIpAgx6toeyojKUYl3CngMMMrVQVTTo5b5F4fluGI"); // 设置微信公众号的EncodingAESKey

		wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
		
		outService=new OutService();
		incomeService=new IncomeService();
		
		//初始化时请求数据服务 防止报错java.lang.IllegalArgumentException: unexpected url: null
		try{
			incomeService.findByMsgIdAndCreateTime(1l,1l,"222");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);

		String signature = request.getParameter("signature");
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");

		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
			// 消息签名不正确，说明不是公众平台发过来的消息
			response.getWriter().println("非法请求");
			return;
		}

		String echostr = request.getParameter("echostr");
		if (StringUtils.isNotBlank(echostr)) {
			// 说明是一个仅仅用来验证的请求，回显echostr
			response.getWriter().println(echostr);
			return;
		}

		String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw"
				: request.getParameter("encrypt_type");
	
		if ("raw".equals(encryptType)) {
			// 明文传输的消息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
			WxMpXmlOutTextMessage outTextMessage=null;
			if(inMessage.getMsgType().equals(WxConsts.XML_MSG_TEXT)){
				String content=inMessage.getContent();
				String[] contentInfo=content.split("[,，]");
				double money=0;
				String type="out";
				if(contentInfo.length>=2){
					String smoney=contentInfo[1];
					if(smoney.indexOf("+")==0){
						smoney=smoney.substring(1);
						type="in";
					}
					try{
						money=Double.parseDouble(smoney);
					}catch(Exception e){
						money=0;
					}
					if(money==0){
						outTextMessage = WxMpXmlOutMessage.TEXT().content("输入金额不正确").fromUser(inMessage.getToUserName())
								.toUser(inMessage.getFromUserName()).build();
					}else{
						if(type.equals("out")){
							String now=Common.nowDate();
							String outId=outService.save(inMessage.getFromUserName(), contentInfo[0], money, 
									inMessage.getMsgId(), inMessage.getCreateTime(),now);
							if(outId!=null && !outId.equals("")){
								double sum=outService.getSumMoneyByDate(now,inMessage.getFromUserName());
								outTextMessage = WxMpXmlOutMessage.TEXT().content("保存成功,今日共消费:"+sum).fromUser(inMessage.getToUserName())
										.toUser(inMessage.getFromUserName()).build();
							}else{
								outTextMessage = WxMpXmlOutMessage.TEXT().content("保存失败").fromUser(inMessage.getToUserName())
										.toUser(inMessage.getFromUserName()).build();
							}
						}else{
							String now=Common.nowDate();
							String inId=incomeService.save(inMessage.getFromUserName(), contentInfo[0], money, inMessage.getMsgId(), 
									inMessage.getCreateTime(),now);
							if(inId!=null && !inId.equals("")){
								double sum=incomeService.getSumMoneyByDate(now,inMessage.getFromUserName());
								outTextMessage = WxMpXmlOutMessage.TEXT().content("保存成功,今日共收入:"+sum).fromUser(inMessage.getToUserName())
										.toUser(inMessage.getFromUserName()).build();
							}else{
								outTextMessage = WxMpXmlOutMessage.TEXT().content("保存失败").fromUser(inMessage.getToUserName())
										.toUser(inMessage.getFromUserName()).build();
							}
						}
					}
				}else{
					outTextMessage = WxMpXmlOutMessage.TEXT().content("格式错误").fromUser(inMessage.getToUserName())
							.toUser(inMessage.getFromUserName()).build();
				}
			}else{
				outTextMessage = WxMpXmlOutMessage.TEXT().content("只支持文本消息").fromUser(inMessage.getToUserName())
						.toUser(inMessage.getFromUserName()).build();
			}
			response.getWriter().write(outTextMessage.toXml());
			return;
		}

		if ("aes".equals(encryptType)) {
			// 是aes加密的消息
			String msgSignature = request.getParameter("msg_signature");
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), config,
					timestamp, nonce, msgSignature);
			WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
			response.getWriter().write(outMessage.toEncryptedXml(config));
			return;
		}

		response.getWriter().println("不可识别的加密类型");
		return;
	}
}
